package com.xvyy.tingshu.common.config.threadpool;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ClassName: ThreadPoolConfiguration
 * Package: com.xvyy.tingshu.common.config.threadpool
 *
 * @Description:
 * @Author: xvyy
 * @Create: 2025/1/25 - 10:35
 * @Version: v1.0
 */
@Configuration
@EnableConfigurationProperties(ThreadPoolProperties.class)
public class ThreadPoolConfiguration {

    Logger logger = LoggerFactory.getLogger(ThreadPoolConfiguration.class);

    @Autowired
    private ThreadPoolProperties threadPoolProperties;

    @Value("${spring.application.name}")
    private String appName;// 应用名称

    @Value("${server.port}")
    private String port;// 端口号

    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {

        // 1. 核心线程数
        int corePoolSize = threadPoolProperties.getCorePoolSize();
        // 2. 最大线程数
        int maximumPoolSize = threadPoolProperties.getMaxPoolSize();
        // 3. 存活时间
        long ttl = threadPoolProperties.getTtl();
        // 4. 时间单位
        TimeUnit unit = threadPoolProperties.getUnit();
        // 5. 阻塞队列   LinkedBlockingQueue<>();不给参数易发生OOM错误
        LinkedBlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<>(threadPoolProperties.getBlockQueueSize());
//        ArrayBlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(1000);
        AtomicInteger atomicInteger = new AtomicInteger(0);// 计数器，保证线程名唯一
        // 6. 线程工厂   自定义线程工厂
        ThreadFactory threadFactory = new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {


                Thread thread = new Thread(r);
//                thread.start();// 这里不用手动启动，底层会自动启动
                //atomicInteger.incrementAndGet();// 计数器+1
                thread.setName(appName + "-" + port + "-thread-" + atomicInteger.incrementAndGet());
                return thread;
            }
        };
        // 7. 拒绝策略
        RejectedExecutionHandler handler = new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution( Runnable r, ThreadPoolExecutor e) {
                logger.error("提交任务：{}被拒绝执行", r.toString());
                // 抛出异常，减少OOM的风险
                throw new RejectedExecutionException("Task " + r.toString() + " rejected from " + e.toString());
            }
        };

        // 8. 返回自定义的线程池对象
        return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, ttl, unit, blockingQueue, threadFactory, handler);
    }


}
